package descentFly.away3D4.Background
{
	import UIUtils.uif_util;
	
	import away3d.materials.SkyBoxMaterial;
	import away3d.materials.utils.CubeMap;
	import away3d.primitives.SkyBox;
	
	import descentFly.away3D4.df_awaySpace;
	import descentFly.away3D4.df_loadSection;
	
	import flash.display.BitmapData;
	import flash.geom.Matrix;
	import flash.geom.Matrix3D;
	import flash.geom.Point;
	
	import space.sp_utils;
	
	public class df_bgSpace extends df_bgSky {
		public static const SIDE_COUNT			: int 		= 6;
		public static const FIELD_BACKIMAGES	: String 	= 'back';
		public static const FIELD_SIZE			: String 	= 'size';
		public static const FIELD_STARCOUNT		: String 	= 'startCount';
		
		public static const DEFAULT_BACKIMAGES	: Array 	= new Array(SIDE_COUNT);
		public static const DEFAULT_SIZE		: int		= 1024;
		public static const DEFAULT_STARCOUNT	: int	 	= 1000;
		
		
		private var _bmp: Array;
		public function df_bgSpace(a_space:df_awaySpace, a_options:Object) {
			a_options = sp_utils.checkParam(a_options, FIELD_BACKIMAGES, DEFAULT_BACKIMAGES);
			a_options = sp_utils.checkParam(a_options, FIELD_SIZE, DEFAULT_SIZE);
			a_options = sp_utils.checkParam(a_options, FIELD_STARCOUNT, DEFAULT_STARCOUNT);
			super(a_space, a_options);
		}
		
		override protected function initialize():void {
			super.initialize();
			_bmp = new Array(SIDE_COUNT);
			var ls: df_loadSection = new df_loadSection();
			options.back.forEach(function(item: Object, i: int, arr: Array): void {
				if (item.url) _bmp[i] = ls.loadBmp(item.url, true, 0);
			})
			ls.endSection(doComplete);
		}
		
		protected function doComplete(): void {
			var v_bmd: Array = new Array(SIDE_COUNT);
			for (var i: int; i<SIDE_COUNT; i++) {
				v_bmd[i] = sp_utils.randomSpace(options[FIELD_STARCOUNT]/SIDE_COUNT, options[FIELD_SIZE]);
				if (_bmp[i]) {
					var mat: Matrix = sp_utils.enterHere(v_bmd[i].rect, _bmp[i].bitmapData.rect.size);
					if (options.back[i].scale) {
						var center: Point = new Point(_bmp[i].width / 2, _bmp[i].height / 2);
						mat.translate(-center.x, -center.y);
						mat.scale(options.back[i].scale, options.back[i].scale);
						mat.translate(center.x, center.y);
					}
					v_bmd[i].draw(_bmp[i], mat);
				}
			}
			var cubeMap: CubeMap = new CubeMap(v_bmd[0], v_bmd[1], v_bmd[2], v_bmd[3], v_bmd[4], v_bmd[5]);
			setSkyBox(new SkyBox(cubeMap));
		}
	}
}